<?php

namespace Home\Controller;

class BuyController extends HomeController
{
    //统计分页总数
    public function buytotal(){
        $buyData = M()->table('trade_adver as a ')
            ->field('a.userid,a.id,a.price,a.money_type,a.pay_type,a.min_price,a.max_limit,a.min_limit,b.username,b.headimg,c.trade_num,c.user_praise,c.user_trust')
            ->join('left join trade_user as b on a.userid = b.id left join trade_user_credit as c on a.userid = c.userid')
            ->where('a.trade_type = 1 and a.status = 1')->select();
        $this->ajaxReturn(count($buyData),'JSON');
    }

    //卖单显示
    public function index($page = 1 , $country = NULL , $money_type = NULL , $pay_type = NULL , $username = NULL)
    {
        if ($username) {
            $where['a.userid'] = M('User')->where(array(
                'username' => $username
            ))->getField('id');
        }

        if ($country) {
            $where['a.country'] = $country;
        }

        if ($money_type) {
            $where['a.pay_type'] = $pay_type;
        }

        $where['a.trade_type'] = 1;

        $where['a.status'] = 1;

        $buyData = M()->table('trade_adver as a ')
            ->field('a.userid,a.id,a.price,a.money_type,a.pay_type,a.min_price,a.max_limit,a.min_limit,a.num,b.username,b.headimg,c.trade_num,c.user_praise,c.user_trust')
            ->join('left join trade_user as b on a.userid = b.id left join trade_user_credit as c on a.userid = c.userid')
            ->where($where)->limit(($page-1) * 15 , 15)->select();
        foreach ($buyData as $k => $v) {
            $buyData[$k]['limit'] = $v['min_limit'] . "-" . $v['max_limit'];
        }

        $this->ajaxReturn($buyData, 'JSON');
    }

    //购买详情  id 为  广告的id
    public function buy_index($id,$userid,$token)
    {
        $this->checkLog($userid, $token);

        $trade_log = M('Trade')->where('order_status != 0 and order_status != 5 and userid = ' .$userid)->select();

        $trade_count = count($trade_log);
        if ($trade_count >= 5){
            $this->ajaxError('您有五笔订单请先完成交易,再提交订单');
        }

        $adverData = M('Adver')->where('status = 1 and id= '.$id)->getField('userid');

        if(!$adverData){
            $this->ajaxError('没有此广告');
        }

        if ($adverData == $userid){
            $this->ajaxError('此广告是您自己发布的，不能进行交易');
        }

        $user = M('User')->where('id = ' .$userid)->find();

        if ($user['sm_is_ok'] != 2) {
            $this->ajaxError('请先完成实名认证');
        }

        $adverData = M()->table('trade_adver as a ')
            ->field('a.num,a.full_num,a.price,a.pay_type,a.min_price,a.max_limit,a.min_limit,a.message,b.id,b.email_is_ok,b.sm_is_ok,b.username,b.headimg,c.trade_num,c.user_praise,c.user_trust')
            ->join('left join trade_user as b on a.userid = b.id left join trade_user_credit as c on a.userid = c.userid')
            ->where('a.id=' . $id)->find();

        $tradeBtcTotal = M('Trade')->field("sum(deal) as 'deal'")->where('order_status >=3 and (userid = ' . $userid . ' or trade_id = ' .$userid .')')->select();
        $adverData['historydeal'] = $tradeBtcTotal[0]['deal'];

        $data = array(
            'adverData' => $adverData,
            'type' => 1,
        );
        $this->ajaxReturn($data, 'JSON');
    }

    //点击购买  id为广告id  cny 为 订单的购买金额  num为订单购买数量
//    public function buy_submit($id = 39, $price = 1000, $num = 0.003, $userid = 38)
    public function buy_submit($id, $price, $num , $userid , $token)
    {

        $this->checkLog($userid, $token);

        if ($price == '') {
            $this->ajaxError('请输入购买金额');
        }

        if ($num == '') {
            $this->ajaxError('请输入购买数量');
        }

        $tradeData = M('Adver')->where("status = 1 and id=" . $id)->find();

        if ($tradeData['num'] == 0) {
            $this->ajaxError('您购买的商品剩余量为0');
        }

        if (!$tradeData){
            $this->ajaxError("您购买的商品已下架");
        }

        $user = M('User')->where(array(
            'id' => $userid
        ))->getField('sm_is_ok');

        if ($user !=2){
            $this->ajaxError('请先去实名认证');
        }

        //TODO 校验是否自买自卖  已修改
        if ($tradeData['userid'] == $userid){
            $this->ajaxError('此广告是您发布的，不能进行交易');
        }

        if($tradeData['num'] < $num){
            $this->ajaxError('您购买的数量超过广告交易数量');
        }

        if ($price < $tradeData['min_limit'] || $price > $tradeData['max_limit']) {
            $this->ajaxError("您的价格不在区间范围内");
        }

        if (! check($price, 'double')) {
            $this->ajaxError('交易价格格式错误');
        }

        if (! check($num, 'double')) {
            $this->ajaxError('交易数量格式错误');
        }

        $res = M('Adver')->where(array(
            'id' => $id
        ))->setInc('numd' , $num);

        if (!$res) {
            $this->ajaxError('修改广告冻结资金失败');
        }

        $res = M('Adver')->where(array(
            'id' => $id
        ))->setDec('num' , $num);

        if (!$res){
            $this->ajaxError('冻结广告资金失败');
        }

        //TODO 订单号生成逻辑，建议时间戳+数据表对应ID方式拼接  已修改
        $order_id = substr(time(),'-4') . $id;

        $rs = M('trade')->add(array(
            'adver_id' => $id,
            'userid' => $userid,
            'trade_id' => $tradeData['userid'],
            'price' => $price,
            'num' => $num,
            'money_type' => $tradeData['money_type'],
            'addtime' => time(),
            'status' => 1,
            'order_status' => 1,
            'type' => 1,
            'order_id' => $order_id,
            'pay_type' => $tradeData['pay_type']
        ));

        if ($rs) {
            $arr = array(
                'type' => 1,
                'order_id' => $rs,
                'msg' => '下单OK'
            );
            $this->ajaxReturn($arr, 'JSON');
        } else {
            $this->ajaxError("下单失败");
        }
    }
}